--- title: "10、砍竹子" created: 2025-11-28 tags: - 算法 --- # 10、砍竹子 ## 题目 [砍竹子](https://www.lanqiao.cn/paper/3822/problem/2117/) ![[image-26f32428.png]] ## 思路分析 贪心+暴力模拟 找到一颗最高的竹子 双指针检查左右是否有连续的一样高的 如果有 就全砍一次 ```cpp #include using namespace std; typedef long long LL; const int N = 2e5 + 10; LL h[N]; int n; int main() { cin >> n; int ac=0; for (int i = 0; i < n; i++) { cin >> h[i]; if(h[i]==1) ac++; } int cnt = 0; while (ac!=n) { // 找到最高的竹子 LL max_height = 0; int idx = -1; for (int i = 0; i < n; i++) { if (h[i] > max_height) { max_height = h[i]; idx = i; } } // 使用双指针找到连续相同高度的竹子 int l = idx - 1, r = idx + 1; while (l >= 0 && h[l] == h[idx]) l--; while (r < n && h[r] == h[idx]) r++; // 对这些竹子使用魔法 LL new_height = floor(sqrt(max_height / 2 + 1)); for (int i = l + 1; i < r; i++){ h[i] = new_height; if(new_height==1) ac++; } cnt++; } cout << cnt; return 0; } ``` 只能过4个 5分 ![[image-766a6eb3.png]] 时间花在了每次双指针找相同上 优化的思路是把相同高度的合并起来(记录l,r) 几个连续相同的是可以合并成一个的 这个技巧在岛屿那题见过 但是考试的时候可能想不到 ## 代码实现 ```cpp #include using namespace std; typedef long long LL; const int N=2e5+10; struct Seg{ int l,r; LL v; bool operator<(const Seg& other)const{ if(v!=other.v) return vother.l; } }; priority_queue heap; LL h[N]; int n; LL f(LL x) { return sqrtl(x / 2 + 1); } int main() { cin>>n; for(int i=0;i>h[i]; for(int i=0;i1 || heap.top().v>1) { auto cut = heap.top(); heap.pop(); while(heap.size() && heap.top().v == cut.v && cut.r + 1 == heap.top().l) { cut.r = heap.top().r;//相邻且等高的合并 heap.pop(); } heap.push({cut.l, cut.r, f(cut.v)}); if (cut.v > 1) cnt++; } cout<